
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../generated/l10n.dart';

class LanguageProvider extends ChangeNotifier {
  Locale? _currentLocale;
  final List<Locale> _locales = [ Locale('en', 'US'), Locale('zh', 'CN')];

  Locale? get currentLocale => _currentLocale;

  LanguageProvider(){
    _loadSavedLocale();
  }


  Future<void> _loadSavedLocale() async {
    final prefs = await SharedPreferences.getInstance();
    final localeString = prefs.getString('locale');
    if (localeString != null) {
      final localeParts = localeString.split('_');
      if (localeParts.length == 2) {
        final locale = Locale(localeParts[0], localeParts[1]);
        if (_locales.contains(locale)) {
          _currentLocale = locale;
          print("init");
          print(locale);
          await S.load(locale);
          notifyListeners();
        }
      }
    }
    if (_currentLocale == null) {
      _currentLocale = _locales.last;
      await S.load(_locales.last);
      _saveLocale(_locales.last);
      notifyListeners();
    }
  }

  Future<void> changeLocale(Locale newLocale) async {
    if (_locales.contains(newLocale)) {
      _currentLocale = newLocale;
      await S.load(newLocale);
      _saveLocale(newLocale);
      notifyListeners();
    }
  }

  void _saveLocale(Locale locale) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setString('locale', '${locale.languageCode}_${locale.countryCode}');
  }
}